package com.example.social.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.social.common.Result;
import com.example.social.dto.CommentDTO;
import com.example.social.dto.PostDTO;
import com.example.social.service.PostService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/post")
@RequiredArgsConstructor
@PreAuthorize("isAuthenticated()")
public class PostController {

    private final PostService postService;

    @PostMapping("/create")
    public Result<PostDTO> createPost(@RequestBody Map<String, Object> request) {
        String content = (String) request.get("content");
        @SuppressWarnings("unchecked")
        List<String> images = (List<String>) request.get("images");
        
        PostDTO post = postService.createPost(content, images);
        return Result.success(post);
    }

    @GetMapping("/list")
    public Result<IPage<PostDTO>> getPosts(
            @RequestParam(defaultValue = "1") Long page,
            @RequestParam(defaultValue = "10") Long size) {
        return Result.success(postService.getPosts(page, size));
    }

    @PostMapping("/{id}/like")
    public Result<Void> toggleLike(@PathVariable Long id) {
        postService.toggleLike(id);
        return Result.success();
    }

    @PostMapping("/{id}/comment")
    public Result<Void> comment(
            @PathVariable Long id,
            @RequestBody Map<String, String> request) {
        String content = request.get("content");
        postService.comment(id, content);
        return Result.success();
    }

    @GetMapping("/{id}/comments")
    public Result<List<CommentDTO>> getComments(@PathVariable Long id) {
        return Result.success(postService.getComments(id));
    }

    @DeleteMapping("/comment/{id}")
    public Result<Void> deleteComment(@PathVariable Long id) {
        postService.deleteComment(id);
        return Result.success();
    }
} 